import React, { PureComponent, Fragment } from 'react';

import { connect } from 'dva';

import moment from 'moment';

import { Row, Col, Card, Form, Input, Select, Icon, Button, Dropdown, Menu, InputNumber, DatePicker, Modal, message, Badge, Divider, Steps, Radio, Popconfirm } from 'antd';

import MyIcon from '@/components/MyIcon';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import StandardTable from '@/containers/StandardTable';
import StandardTableHandle from '@/containers/StandardTable/StandardTableHandle';

import { miniApps as tabList } from '@/commons/tabList';
import { feedbacks as columns } from '@/commons/columns';

import styles from './style.less';

const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea } = Input;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
  .map(key => obj[key])
  .join(',');

/* eslint react/no-multi-comp:0 */
@connect(({ feedbacks, loading }) => ({
  feedbacks,
  loading: loading.models.feedbacks,
}))
@Form.create()
class TableList extends PureComponent {
  state = {
    selectedRows: [],
    row: {},
  };

  columns = [...columns, {
    title: '操作',
    width: 99,
    align: 'center',
    fixed: 'right',
    render: ({ id, status }) => (
      <Popconfirm title="确认标记为已阅?" onConfirm={this.handleUpdate.bind(null, id)} okText="确认" cancelText="取消">
        <Button icon="edit" type="primary" size="small" disabled={status}>{status ? '已阅' : '未阅'}</Button>
      </Popconfirm>
    ),
  }];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'feedbacks/fetch',
    });
  }

  handleTabChange = type => {
    const { form, dispatch } = this.props;
    form.resetFields();

    dispatch({
      type: 'feedbacks/fetch',
      payload: { type },
    });
  }

  handleUpdate = id => {
    const { dispatch } = this.props;

    dispatch({
      type: 'feedbacks/update',
      payload: { id },
      callback: ({ errno, data }) => {
        if (errno) {
          message.error('已审阅失败！');
        } else {
          dispatch({
            type: 'feedbacks/fetch',
          });

          message.success(`序号${id}的问题反馈已审阅成功~`);
        }
      }
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      from: pagination.current,
      size: pagination.pageSize,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'feedbacks/fetch',
      payload: params,
    });
  };

  handleMenuClick = e => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;
    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'feedbacks/remove',
          payload: { id: selectedRows.map(row => row.id) },
          callback: ({ errno, data }) => {
            if (!errno && data) {
              dispatch({
                type: 'feedbacks/fetch'
              });
              this.setState({
                selectedRows: []
              });
              message.success(`共有${data}条问题反馈删除成功~`);
            } else {
              message.error('删除失败！');
            }
          },
        });
        break;
      default:
        break;
    }
  };

  handleSelectRows = rows => {
    this.setState(state => ({
      ...state,
      selectedRows: rows,
    }));
  };

  handleToggleTable = e => {
    e.preventDefault();

    const { form, dispatch } = this.props;
    form.resetFields();

    dispatch({
      type: 'feedbacks/fetch',
      payload: { status: e.target.value }
    });
  }

  render() {
    const {
      feedbacks: { data, type, status },
      loading,
    } = this.props;
    const { selectedRows } = this.state;

    return (
      <PageHeaderWrapper 
        title="问题反馈" 
        action={moment().format('LLLL')}
        tabList={tabList}
        tabActiveKey={String(type)}
        onTabChange={this.handleTabChange}
      >
        <Card bordered={false}>
          <StandardTableHandle
            status={status}
            selectedRows={selectedRows}
            radioGroups={{
              'all': <Fragment><Icon type="appstore" />&nbsp;全部</Fragment>,              
              '0': <Fragment><MyIcon type="icon-review" />&nbsp;待审阅</Fragment>,
              '1': <Fragment><MyIcon type="icon-preview" />&nbsp;已审阅</Fragment>,
            }}
            menuItems={{'remove': <Button type="danger" icon="delete">删除</Button>}}
            action={<a href="/favicon.png" target="_blank"><Button type="primary" icon="download">EXCEL</Button></a>}
            onToggleTable={this.handleToggleTable}
            onMenuClick={this.handleMenuClick}
          />
          <StandardTable
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            scroll={{ x: 1300 }}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default TableList;